package com.ruoyi.attachedData.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.ruoyi.attachedData.domain.AttachedData;
import com.ruoyi.attachedRecord.domain.AttachedRecord;
import com.ruoyi.attachedRecord.mapper.AttachedRecordMapper;
import com.ruoyi.commission.domain.Commission;
import com.ruoyi.commission.service.ICommissionService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.engineering.domain.Engineering;
import com.ruoyi.notice.domain.Notice;
import com.ruoyi.notice.service.INoticeService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.task.domain.Task;
import com.ruoyi.task.service.ITaskService;
import com.ruoyi.weeklyReport.domain.WeeklyReport;
import com.ruoyi.weeklyReport.service.IWeeklyReportService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.attachedData.mapper.AttachedDataMapper;
import com.ruoyi.attachedData.service.IAttachedDataService;

import javax.annotation.Resource;

/**
 * 附详情Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-09
 */
@Service
public class AttachedDataServiceImpl implements IAttachedDataService
{
    @Autowired
    private AttachedDataMapper attachedDataMapper;

    @Resource
    private AttachedRecordMapper attachedRecordMapper;

    @Autowired
    private IWeeklyReportService weeklyReportService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private ICommissionService commissionService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private INoticeService noticeService;

    /**
     * 查询附详情
     *
     * @param id 附详情主键
     * @return 附详情
     */
    @Override
    public AttachedData selectAttachedDataById(Long id)
    {
        AttachedData attachedData = attachedDataMapper.selectAttachedDataById(id);
        return attachedData;
    }

    @Override
    public List<AttachedData> selectAttachedDataListCount(AttachedData attachedData){
        List<AttachedData> attachedDataList = attachedDataMapper.selectAttachedDataListCount(attachedData);
        return attachedDataList;
    }

    /**
     * 查询附详情列表
     *
     * @param attachedData 附详情
     * @return 附详情
     */
    @Override
    public List<AttachedData> selectAttachedDataList(AttachedData attachedData)
    {
        List<AttachedData> attachedDataList = attachedDataMapper.selectAttachedDataList(attachedData);
        if(!attachedDataList.isEmpty()) {
            AttachedRecord attachedRecord = new AttachedRecord();
            for (AttachedData attachedData1 : attachedDataList) {
                Integer completionNumber = 0;
                attachedRecord.setAttachedDataId(attachedData1.getId());
                List<AttachedRecord> attachedRecordList = attachedRecordMapper.selectAttachedRecordList(attachedRecord);
                if (!attachedRecordList.isEmpty()) {
                    for (AttachedRecord attachedData2 : attachedRecordList) {
                        if(StringUtils.isNotEmpty(attachedData2.getTestNumber())){
                            completionNumber += Integer.parseInt(attachedData2.getTestNumber());
                        }
                    }
                }
                attachedData1.setCompletionProgress(String.valueOf(completionNumber));
            }
        }
        return attachedDataList;
    }

    /**
     * 新增附详情
     *
     * @param attachedData 附详情
     * @return 结果
     */
    @Override
    public int insertAttachedData(AttachedData attachedData)
    {
        attachedData.setCreateTime(DateUtils.getNowDate());
        Integer isAttacheData = attachedDataMapper.insertAttachedData(attachedData);

        Commission commissionOne = commissionService.selectCommissionById(attachedData.getCommissionId());
        SysUser userOne = userService.selectUserById(commissionOne.getBusinessManagerId());

        //任务增加一条（试验人 不为空）
        if(attachedData.getChargePerson() != null){
            //进度管理增加一条
            WeeklyReport weeklyReport = new WeeklyReport();
            weeklyReport.setCommissionId(attachedData.getCommissionId());
            weeklyReport.setEngineeringId(attachedData.getEngineeringId());
            weeklyReport.setEnterpriseId(commissionOne.getEnterpriseId());
            weeklyReport.setAttachedDataId(attachedData.getId());
            weeklyReport.setTotal(Long.valueOf(attachedData.getAmount()));//工程总量
            weeklyReport.setTestProject(attachedData.getTestMethod());//试验项目
            weeklyReport.setProjectManagerName(userOne.getNickName());
            weeklyReportService.insertWeeklyReport(weeklyReport);

            Task task = new Task();
            task.setCommissionId(attachedData.getCommissionId());
            task.setEngineeringId(attachedData.getEngineeringId());
            task.setTaskType("检测数据录入");
            task.setStatus("0");
            task.setTaskContent(commissionOne.getEngineeringName() + "的委托单" + commissionOne.getNumber() +"的试验项目："+attachedData.getTestMethod()+"已分配，请及时检测。");
            task.setChargePerson(attachedData.getChargePerson());
            taskService.insertTask(task);

            //更新之前任务
            Task task1 = new Task();
            task1.setTaskType("分配试验项目");
            task1.setCommissionId(attachedData.getCommissionId());
            List<Task> taskList = taskService.selectTaskList(task1);
            if(taskList.size() > 0){
                task1.setId(taskList.get(0).getId());
                task1.setStatus("1");
                task1.setExecuteTime(DateUtils.getNowDate());
                taskService.updateTask(task1);
            }

            //录入通知 给 劳务经理
            Notice notice = new Notice();
            notice.setCommissionId(commissionOne.getId());
            notice.setEngineeringId(commissionOne.getEngineeringId());
            notice.setNoticType("录入通知");
            notice.setNoticContent(commissionOne.getEngineeringName()+"的委托单"+commissionOne.getNumber()+"已受理,请及时录入数据");
            notice.setUserId(attachedData.getChargePerson());
            noticeService.insertNotice(notice);
        }

        return isAttacheData;
    }

    /**
     * 修改附详情
     *
     * @param attachedData 附详情
     * @return 结果
     */
    @Override
    public int updateAttachedData(AttachedData attachedData)
    {
        AttachedData attachedDataOne = attachedDataMapper.selectAttachedDataById(attachedData.getId());
        if(attachedDataOne.getChargePerson() == null || ! (attachedDataOne.getChargePerson().equals(attachedData.getChargePerson()) ) ){
            Commission commissionOne = commissionService.selectCommissionById(attachedDataOne.getCommissionId());
            Task task = new Task();
            task.setCommissionId(attachedData.getCommissionId());
            task.setEngineeringId(attachedData.getEngineeringId());
            task.setTaskType("检测数据录入");
            task.setStatus("0");
            task.setTaskContent(commissionOne.getEngineeringName() + "的委托单" + commissionOne.getNumber() +"的试验项目："+attachedData.getTestMethod()+"已分配，请及时检测。");
            task.setChargePerson(attachedData.getChargePerson());
            taskService.insertTask(task);

            //更新之前任务
            Task task1 = new Task();
            task1.setTaskType("分配试验项目");
            task1.setCommissionId(attachedData.getCommissionId());
            List<Task> taskList = taskService.selectTaskList(task1);
            if(taskList.size() > 0){
                task1.setId(taskList.get(0).getId());
                task1.setStatus("1");
                task1.setExecuteTime(DateUtils.getNowDate());
                taskService.updateTask(task1);
            }

            //录入通知 给 劳务经理
            Notice notice = new Notice();
            notice.setCommissionId(commissionOne.getId());
            notice.setEngineeringId(commissionOne.getEngineeringId());
            notice.setNoticType("录入通知");
            notice.setNoticContent(commissionOne.getEngineeringName()+"的委托单"+commissionOne.getNumber()+"已受理,请及时录入数据");
            notice.setUserId(attachedData.getChargePerson());
            noticeService.insertNotice(notice);
        }

        attachedData.setUpdateTime(DateUtils.getNowDate());
        return attachedDataMapper.updateAttachedData(attachedData);
    }


    @Override
    public int updateAttachedDataForStatus(Long commissionId)
    {
        return attachedDataMapper.updateAttachedDataForStatus(commissionId);
    }

    /**
     * 批量删除附详情
     *
     * @param ids 需要删除的附详情主键
     * @return 结果
     */
    @Override
    public int deleteAttachedDataByIds(Long[] ids)
    {
        return attachedDataMapper.deleteAttachedDataByIds(ids);
    }


    /**
     * 批量逻辑删除附详情
     *
     * @param ids 需要删除的附详情主键
     * @return 结果
     */
    @Override
    public int logicDeleteAttachedData(Long[] ids,String delType,Long delUser)
    {
        return attachedDataMapper.logicDeleteAttachedData(ids,delType,delUser);
    }

    /**
     * 删除附详情信息
     *
     * @param id 附详情主键
     * @return 结果
     */
    @Override
    public int deleteAttachedDataById(Long id)
    {
        return attachedDataMapper.deleteAttachedDataById(id);
    }


    /**
     * 导入数据
     *
     * @param attachedDataList 数据列表
     * @return 结果
     */
    @Override
    public String importAttachedData(List<AttachedData> attachedDataList,Long attachedId,Long commissionId,Long engineeringId,Long type)
    {
        if (StringUtils.isNull(attachedDataList) || attachedDataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (AttachedData attachedData : attachedDataList)
        {
            try
            {
                attachedData.setCreateBy(SecurityUtils.getUserId());
                attachedData.setAttachedId(attachedId);
                attachedData.setCommissionId(commissionId);
                attachedData.setEngineeringId(engineeringId);
                attachedData.setType(type);
                attachedDataMapper.insertAttachedData(attachedData);
                successNum++;
                successMsg.append("<br/>" + successNum + "、桩号 " + attachedData.getPileNumber() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、桩号 " + attachedData.getPileNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
//                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
